import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    component: () => import('../components/login/Login')
  },,
  {
    path: '/register',
    component: () => import('../components/login/Register')
  },
  {
      path: '/home',
      component: () => import('../components/admin/Home'),
      redirect: '/firstPage',
      children: [
        {
          path: '/firstPage',
          component: () => import('../components/admin/FirstPage')
        },
        {
          path: '/device',
          component: () => import('../components/admin/Device')
        },
        {
          path: '/room',
          component: () => import('../components/admin/Room')
        },
        {
          path: '/user',
          component: () => import('../components/admin/User')
        },
      ]
  },
  {
    path:'/userhome',
    component:() => import('../components/users/UserHome'),
    redirect: '/userPage',
    children: [
        {
          path: '/userPage',
          component:() => import('../components/users/UserPage')
        },
        {
          path:'/dataCollect',
          component:() => import('../components/users/DataCollect')
        },
        {
          path:'/personal',
          component:() => import('../components/users/Personal')
        },
        {
          path:'/dataAnalyse',
          component:() => import('../components/users/DataAnalyse')
        },
    ]
  }
]


const router = new VueRouter({
  base: process.env.BASE_URL,
  routes
})


// 挂载路由导航守卫
router.beforeEach((to, from, next) => {
  if(to.path === '/login' || to.path === '/register') {
    return next();
  }
  const tokenStr = window.sessionStorage.getItem('token');
  if(!tokenStr) {
    return next('/login');
  }else {
    next();
  }
})

export default router
